#!/bin/bash

#get the server process

SERVICENAME=`pgrep -f -l 'perl.*server/slim' | sed -n -e 's/^.*share\/\([[:alpha:]]*\)\/.*/\1/p'`

if [ -z $SERVICENAME ]; then
  #echo 'Trying again to get SERVICENAME..'
  SERVICENAME=`pgrep -fl 'perl.*squeezeboxserver' | sed -n -e 's/^.*\(squeezeboxserver\).*$/\1/p'`
fi

#echo "Service: ${SERVICENAME}"

if [ -d /run/lock ]; then
  BLOCKFILE=/run/lock/spc-block
else
  BLOCKFILE=/var/lock/spc-block
fi

echo 'hardblock' >$BLOCKFILE

# If we figured out the service...
if [ ! -z $SERVICENAME ]; then
  #get the process user id
  USERID=`ps aux | egrep "perl.*${SERVICENAME}" | sed -n -e 's/^\([[:alnum:]]*\)[[:blank:]]*.*$/\1/p'`
  USERID=`echo $USERID | sed -e 's/root//g'`
else
  USERID='squeezeboxserver'
fi



#get the process username
USERNAME=`getent passwd $USERID | sed -n -e 's/^\([[:alnum:]]*\):.*$/\1/p'`

#get the process group
USERGROUP=`id -ng $USERNAME`

#echo "Service: ${SERVICENAME}"
#echo "User ID: ${USERID}"
#echo "User:    ${USERNAME}"
#echo "Group:   ${USERGROUP}"

if [ -f $BLOCKFILE ]; then
  chown $USERNAME:$USERGROUP $BLOCKFILE
  chmod a+rw $BLOCKFILE
  echo "SrvrPowerCtrl Block file $BLOCKFILE created."
else
  echo "Cannot create SrvrPowerCtrl block file $BLOCKFILE!"
fi

